package game.mapviewer.commands 
{
	import core.Command;
	import flash.display.DisplayObject;
	import flash.display.SimpleButton;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import game.mapviewer.MapViewer;
	/**
	 * ...
	 * @author rnk
	 */
	public class SelectProvinceToMoveCommand extends Command
	{
		private var mapView:MapViewer;
		private var destinationProvinces:Array;
		private var destSelectCallback:Function;
		private var fromProvinceUid:String;
		private var buttons:Array;
		
		public function SelectProvinceToMoveCommand(mapView:MapViewer,fromProvinceUid:String,destinationProvinces:Array,callback:Function) 
		{
			this.destinationProvinces = destinationProvinces;
			this.mapView = mapView;
			this.destSelectCallback = callback;
			this.fromProvinceUid = fromProvinceUid;
		}
		
		override public function Execute():void 
		{
			
			//add source(cancel tipa)
			destinationProvinces.push(fromProvinceUid);
			
			//put march buttons in destination provs
			buttons = [];
			for each (var puid:String in destinationProvinces) 
			{
				var provHolder:DisplayObject = mapView.GetProvinceHolder(puid);
				
				if (puid == fromProvinceUid)
				var marchButton:SimpleButton = new cancel_button();
				else
				marchButton = new march_button();
				
				marchButton.x = provHolder.x - marchButton.width / 2;
				marchButton.y = provHolder.y - marchButton.height / 2;
				marchButton.name = puid;
				mapView.buttonsLayer.addChild(marchButton);
				buttons.push(marchButton);
				marchButton.addEventListener(MouseEvent.CLICK, OnButtonClick);
			}
			
			
		}
		
		private function OnButtonClick(e:Event):void
		{
			//get what we clicked
			var idx:int = buttons.indexOf(e.target);
			var clickedProvUid:String = buttons[idx].name;
			
			//remove march buttons
			for each (var item:SimpleButton in buttons) 
			{
				item.removeEventListener(MouseEvent.CLICK, OnButtonClick);
				mapView.buttonsLayer.removeChild(item);
			}
			buttons = [];
			
			destSelectCallback(clickedProvUid);
			
			Callback();
		}
		
	}

}